import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class BusSchedule {
	// Arrays for holding the bus schedule time tables. 
	private ArrayList<Date> weekdays = new ArrayList<Date>();
	private ArrayList<Date> sat = new ArrayList<Date>();
	private ArrayList<Date> sun = new ArrayList<Date>();
	// Store bus ID.
	private String busID;
	// Store bus destination.
	private String destination;
	// Store the bus's next actual arrival time.
	private Date nextArrivalTime;
	
	// Initialize a random number generator for generating the actual arrival times. 
	private static Random ranGen = new Random(1);
	
	// Get the next actual arrival time. If the next actual arrival time has not
	// been generated yet, generate one.
	public Date getNextArrivalTime() {
		// Get the current time.
		Calendar now = Calendar.getInstance();
		// Initialize a temporary time variable for later use.
		Calendar c = Calendar.getInstance();
		
		// Only generate new arrival time if there is not one or the last arrival time has out dated.
		if (nextArrivalTime == null || now.getTime().after(nextArrivalTime)) {
			ArrayList<Date> useSchedules;
			// Determine which time table to use based on Today's date.
			switch (now.get(Calendar.DAY_OF_WEEK)) {
			case Calendar.SATURDAY:
				useSchedules = sat;
				break;
			case Calendar.SUNDAY:
				useSchedules = sun;
				break;
			default:
				useSchedules = weekdays;
			}
			
			// Find the next scheduled time based on the time table.
			for (Date t: useSchedules) {
				// Initialize the temporary time variable for holding the scheduled times.
				c.setTime(t);
				c.set(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DATE));
				
				// Iterate the schedules until the schedule is after the current time, and
				// generate an actual arrival time around that scheduled arrival time.
				if (c.after(now)) {
					// The actual arrival time will be -2 to 2 minutes from the scheduled time. 
					int delay = ranGen.nextInt(5) - 2;
					
					c.add(Calendar.MINUTE, delay);
					this.nextArrivalTime = c.getTime();
					break;
				}
				
			}
		}		
		
		return nextArrivalTime;
	}

	// Get/set methods for accessing the instance variables. 
	
	public String getDestination() {
		return destination;
	}

	public void setDestination(String destination) {
		this.destination = destination;
	}

	public String getBusID() {
		return busID;
	}

	public void setBusID(String busID) {
		this.busID = busID;
	}

	public ArrayList<Date> getSat() {
		return sat;
	}

	public ArrayList<Date> getSun() {
		return sun;
	}

	public ArrayList<Date> getWeekdays() {
		return weekdays;
	}
}
